package com.example.condition;

import com.example.anno.MyConditionalOnClass;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

public class OnClassCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> attrs =
                metadata.getAnnotationAttributes(MyConditionalOnClass.class.getName());
        if (attrs == null) {
            return false;
        }
        String[] candidates = (String[]) attrs.get("value");
        for (String clazz : candidates) {
            if (!isPresent(clazz)) return false;
        }
        return true;
    }

    private boolean isPresent(String className) {
        try {
            Class.forName(className, false, getClass().getClassLoader());
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
}
